package com.weishui.downloading.download;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.net.Proxy.Type;


public class DwnLoadOperator {

	private URL url;
	private String downLoadtargetDir;
	private int downLoadThreadCount;
	private Proxy proxy;
	public static int DOWNLAOD_COUNT = 0;
	
	private String downLoadFileName;
	
	public DwnLoadOperator(URL url,String downLoadtargetDir,int downLoadThreadCount,Proxy proxy){
		this.url = url;
		this.downLoadtargetDir = downLoadtargetDir;
		this.downLoadThreadCount = downLoadThreadCount;
		this.proxy = proxy;
	}
	
	public void downLoad(){
		URLConnection urlConnection;
		downLoadFileName = url.getPath().substring(url.getPath().lastIndexOf("/") + 1);
		try {
			if(proxy == null){
				urlConnection = url.openConnection();
			}else{
				urlConnection = url.openConnection(proxy);
			}
			//数据长度
			int contentLength = urlConnection.getContentLength();
			int eachThreadDownLoadLength = contentLength/downLoadThreadCount + 1;
			for(int i=0;i<downLoadThreadCount;i++){
				int downLoadlength = eachThreadDownLoadLength;
		        if (i == (downLoadThreadCount - 1)) {
		        	downLoadlength = contentLength - i * eachThreadDownLoadLength;
		        }
		        Thread downLoadThread = new Thread(new DownLoadThread(url,downLoadlength,i*eachThreadDownLoadLength,downLoadtargetDir + downLoadFileName + ".part" + i,proxy));
		        downLoadThread.start();
			}
			//开始下载
			Thread mergeFilesThread = new Thread(new MergeFilesThread(downLoadtargetDir+downLoadFileName,downLoadThreadCount));
			mergeFilesThread.start();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public static void main(String[] args) throws UnknownHostException, MalformedURLException {
		String proxyIp = "10.0.128.6";
		int port = 3128;
		InetSocketAddress socketAddress=new InetSocketAddress(  
                InetAddress.getByName(proxyIp),port);  
        Proxy proxy=new Proxy(Type.HTTP,socketAddress);  
        String urlPath = "http://zhangmenshiting2.baidu.com/data2/music/5240950/5240950.mp3?xcode=3c810868579a4d95a7affb684e8db4ba&mid=0.41967440922247";
		URL url = new URL(urlPath);
		String dir = "D:\\download";
		
		DwnLoadOperator dwnLoadOperator = new DwnLoadOperator(url,dir + "\\",10,proxy);
		
		dwnLoadOperator.downLoad();
		
	}
}
